﻿using System;

#if UNITY_WSA&&!UNITY_EDITOR
using System.Threading.Tasks;
#else
using System.Threading;
#endif

namespace Nijie.Network
{
    public class Thread
    {
#if UNITY_WSA && !UNITY_EDITOR
        Task task;
#else
        System.Threading.Thread task;
#endif
#if UNITY_WSA && !UNITY_EDITOR
        public Thread(Action action)
        {
            task = new Task(action);
            state = States.Stoped;
        }
#else
        public Thread(ThreadStart action)
        {
            task = new System.Threading.Thread(action);
            state = States.Stoped;
        }
#endif
        public bool IsAlive
        {
            get
            {
                return task != null &&
#if UNITY_WSA && !UNITY_EDITOR
                    !task.IsCompleted;
#else
                    task.IsAlive;
#endif
            }
        }
        public void Start()
        {
            task.Start();
            state = States.Running;
        }
        public States state = States.Stoped;
        public enum States
        {
            Running, Stoping, Stoped
        }
        public bool IsVail
        {
            get { return state == States.Running; }
        }
        public States State
        {
            get
            {
                if (state == States.Stoping)
                    if (!IsAlive)
                        state = States.Stoped;
                return state;
            }
        }
        public void Abort()
        {
            state = States.Stoping;
        }
#if UNITY_WSA && !UNITY_EDITOR
        public static Task Sleep(int millisecondsDelay)
        {
            return Task.Delay(millisecondsDelay);
        }
#else
        public static void Sleep(int millisecondsDelay)
        {
            System.Threading.Thread.Sleep(millisecondsDelay);
        }
#endif
    }

}
